package adminlte.config;

        import org.springframework.context.annotation.Configuration;
        import org.springframework.security.config.annotation.web.builders.HttpSecurity;
        import org.springframework.security.config.http.SessionCreationPolicy;
        import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
        import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
        import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * OAuth2不定义ResourceServer，认证鉴权采用方式为：
 *  客户端请求并授权后，oauth2会写一个JSESSIONID到客户端，后续客户端请求只要cookie中
 *  有这个会话id即可，oauth2每次收到请求会首先到session中获取授权信息，获取不到则返回401
 *  ,所以即使携带access_token访问一样会导致401 unauthorized，
 *  避免此问题需要启用EnableResourceServer注解，会增加OAuth2AuthenticationProcessingFilter过滤器
 *  ，该过滤器处理通过access_token访问才会生效
 *
 *  EnableResourceServer注解会启用OAuth2的token认证，在原基础上增加OAuth2AuthenticationProcessingFilter过滤器
 *   EnableResourceServer->(import ResourceServerConfiguration)->configure(http)->ResourceServerSecurityConfigurer
 *   -> OAuth2AuthenticationProcessingFilter
 * @author ZHUFEIFEI
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //此处是关键，默认stateless=true，只支持access_token形式，
        // OAuth2客户端连接需要使用session，所以需要设置成false以支持session授权
        resources.stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();

        //需要的时候创建session，支持从session中获取认证信息，ResourceServerConfiguration中
        //session创建策略是stateless不使用，这里其覆盖配置可创建session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
    }
}
